package com.blueseaapps.utility;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import se.msc.android.droidcouch.DroidCouch;
import android.util.Log;

public class RegistrationTokenManager {

	private static final String LOG_TAG = RegistrationTokenManager.class.getSimpleName();
    private static final String HOST_URL = "https://blueseaappstest.cloudant.com/";
	private static final String DATABASE_NAME = "photoquiz";

	public static boolean storeToken(String regId, String docId) {
		boolean status = false;
		status = DroidCouch.authenticate(HOST_URL, "blueseaappstest", "blueseaapps123");
		if(status){
			Map<String, Object> objMap = new HashMap<String, Object>();
			JSONObject response = DroidCouch.getDocument(HOST_URL, DATABASE_NAME, docId);
			String revId = getRevisionId(response);
			if(revId != null){
				objMap.put("_rev", revId);
			}
			objMap.put("LastUpdate", System.currentTimeMillis());
			objMap.put("RegId", regId);
			JSONObject obj = new JSONObject(objMap);
			String new_rev_id = DroidCouch.updateDocument(HOST_URL, DATABASE_NAME, docId, obj);
			if(new_rev_id != revId){
				status = true;
			}
		}
		return status;
	}

	private static String getRevisionId(JSONObject response) {
		String oldRevId = null; 
			try {
				oldRevId = response.getString("_rev");
			} catch (JSONException e) {
				Log.d(LOG_TAG, "RevId not found");
			}
		return oldRevId;
	}

}
